package queue;

public class LoopQueue<E> implements Queue<E> {
    private E[] data;
    private int front, tail;
    private int size;
    // 先来个构造函数

    public LoopQueue(int capacity) {
        data = (E[]) new Object[capacity];
        front = 0;
        tail = 0;
        size = 0;
    }

    public LoopQueue() {
        this(10);
    }

    // 获取容量
    public int getCapacity() {
        return data.length - 1;
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return front == tail;
    }

    // 实现入队操作，由于是循环队列，需要考虑到达容器的末尾的时候，要取余从头开始存放元素
    @Override
    public void enqueue(E e) {
        if ((tail + 1) % data.length == front) {
            resize(getCapacity() * 2);
        }
        data[tail] = e;
        tail = (tail + 1) % data.length;
        size++;
    }

    public void resize(int newCapacity) {
        E[] newData = (E[]) new Object[newCapacity + 1];
        for (int i = 0; i < data.length; i++) {
            newData[i] = data[(i + front) % data.length];
        }
        data = newData;
        front = 0;
        tail = size;
    }

    @Override
    public E dequeue() {
        // 首先判断是否为空
        if (isEmpty()){
            throw new IllegalArgumentException("cannot dequeue from an empty queue");
        }
        E deq = data[front];
        data[front] = null;
        front = (front + 1) % data.length;
        size--;
        // 出栈的时候，需要考虑容器缩容的问题，节省空间
        if (size == data.length / 4 && getCapacity() / 2 != 0){
            resize(getCapacity() / 2);
        }
        return deq;
    }

    @Override
    public E getFront() {
        // 需要判断队列是否为空
        if (isEmpty()){
            throw new IllegalArgumentException("cannot getFront from an empty queue");
        }
        return data[front];
    }

    // 重写toString方法
    @Override
    public String toString(){
        StringBuilder sb = new StringBuilder();
        sb.append("front [");
        for (int i = front; i != tail; i++){
            sb.append(data[i]);
            if ((i+1) % data.length != tail){
                sb.append(" ,");
            }
        }
        sb.append("] tail\ncapacity:" + getCapacity());
        return sb.toString();
    }
}
